<?php


namespace app\common\service;

// 处理业务

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class ImportData extends ServiceBase
{
    /**
     * 数据导出
     * @param $data array 需要导出的数据
     * @param $title array 导出的数据标题栏
     * @param $fileName string 导出的文件名
     * @param $fileName string 导出的文件类型
     */
    public function ImportData($data,$title,$fileName,$writerType = 'Xlsx')
    {
        // Create new Spreadsheet object
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();

        //表头
        //设置单元格内容
        $titCol = 'A';
        foreach ($title as $key => $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol . '1', $value);
            $titCol++;
        }

        $row = 2; // 从第二行开始
        foreach ($data as $item) {
            $dataCol = 'A';
            foreach ($item as $value) {
                // 单元格内容写入
                $sheet->setCellValue($dataCol . $row, $value);
                $sheet->getStyle($dataCol.$row)->getAlignment()->setWrapText(true);
                $sheet->getStyle($dataCol.$row)->getAlignment()->setHorizontal('center');
                $dataCol++;
            }
            $row++;
        }

        $spreadsheet->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header("Content-Disposition: attachment;filename=$fileName");
        header('Cache-Control: max-age=0');

        // Save
        $writer = IOFactory::createWriter($spreadsheet, $writerType);
//        var_dump($writer);die;
        $writer->save('php://output');

        // $fileName = iconv("utf-8", "gb2312", $fileName);

//        // $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($objPHPExcel, 'Xlsx');
//        $writer = new Xlsx($spreadsheet);
//        $writer->save('php://output'); // 文件通过浏览器下载
        exit();
    }
}